package com.bkgy.modular.tbpaopianpdodata.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bkgy.excelhandle.PlanExcelHandlerImpl;
import com.bkgy.modular.tbpaopianpdodata.dao.TbPaopianPdoDataDao;
import com.bkgy.modular.tbpaopianpdodata.entity.*;
import com.bkgy.modular.tbpaopianpdodata.service.TbPaopianPdoDataService;
import com.bkgy.modular.tbpaopianpdodata.service.impl.TbPaopianPdoDataServiceImpl;
import com.bkgy.sys.common.entity.JCommon;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.util.CodiUtil;
import com.bkgy.util.ExcelUtilsPOI;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 连退跑偏历史记录控制器层
 *
 * @author 生成器生成
 * @date 2022-08-03 17:10:29
 */
@RestController
@RequestMapping("/tbPaopianPdoData")
public class TbPaopianPdoDataController {

    @Autowired
    private TbPaopianPdoDataService tbPaopianPdoDataService;

    @Resource
    private TbPaopianPdoDataDao tbPaopianPdoDataDao;
    @Autowired
    TbPaopianPdoDataServiceImpl tbPaopianPdoDataServiceImpl;

    /**
     * 添加记录
     *
     * @param data userId 用户id
     * @param data sname 用户姓名
     */
    @CrossOrigin
    @RequestMapping(value = {"/insert"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData insertDataTbPaopianPdoData(@RequestBody String data, @RequestHeader(value = "loginToken") String loginToken) {
        JCommon common = JSON.parseObject(loginToken, JCommon.class);
        String sname = common.getSname();
        Long userId = common.getUserId();
        return tbPaopianPdoDataService.insertDataTbPaopianPdoData(data, userId, CodiUtil.returnLm(sname));
    }

    /**
     * 根据主键删除对象
     *
     * @param data json字符串
     */
    @CrossOrigin
    @RequestMapping(value = {"/deleteOne"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData deleteDataTbPaopianPdoDataOne(@RequestBody String data) {
        try {
            JTbPaopianPdoData jtbPaopianPdoData = JSON.parseObject(data, JTbPaopianPdoData.class);
            return tbPaopianPdoDataService.deleteDataTbPaopianPdoDataOne(jtbPaopianPdoData.getIndocno());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("访问接口错误，错误信息为" + e.getMessage(), null);
        }
    }

    /**
     * 根据主键字符串删除多个对象
     *
     * @param data json字符串
     */
    @CrossOrigin
    @RequestMapping(value = {"/deleteMany"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData deleteDataSysUserMany(@RequestBody String data) {
        try {
            JTbPaopianPdoData jtbPaopianPdoData = JSON.parseObject(data, JTbPaopianPdoData.class);
            return tbPaopianPdoDataService.deleteDataTbPaopianPdoDataMany(jtbPaopianPdoData.getStr_indocno());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("访问接口错误，错误信息为" + e.getMessage(), null);
        }
    }

    /**
     * 修改记录
     *
     * @param data       json字符串
     * @param loginToken 请求头参数字符串对象
     */
    @CrossOrigin
    @RequestMapping(value = {"/update"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData updateDataTbPaopianPdoData(@RequestBody String data, @RequestHeader(value = "loginToken") String loginToken) {
        JCommon common = JSON.parseObject(loginToken, JCommon.class);
        String sname = common.getSname();
        Long userId = common.getUserId();
        return tbPaopianPdoDataService.updateDataTbPaopianPdoData(data, userId, CodiUtil.returnLm(sname));
    }

    /**
     * 分页查看记录
     *
     * @param data json字符串
     */
    @CrossOrigin
    @RequestMapping(value = {"/findByPage"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData findDataTbPaopianPdoDataByPage(@RequestBody String data) {
        return tbPaopianPdoDataService.findDataTbPaopianPdoDataByPage(data);
    }

    /**
     * 不分页查看记录
     *
     * @param data json字符串
     */
    @CrossOrigin
    @RequestMapping(value = {"/findByPage3"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData findDataTbPaopianPdoDataByPage3(@RequestBody String data) {
        return tbPaopianPdoDataService.findDataTbPaopianPdoDataByPage3(data);
    }

    /**
     * 分页查看记录
     *
     * @param data json字符串
     */
    @CrossOrigin
    @RequestMapping(value = {"/findByPage2"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData findDataTbPaopianPdoDataByPage2(@RequestBody String data) {
        return tbPaopianPdoDataService.findDataTbPaopianPdoDataByPage2(data);
    }


    /**
     * 根据主键查询单条记录
     *
     * @param data json字符串
     */
    @CrossOrigin
    @RequestMapping(value = {"/findByIndocno"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData findDataTbPaopianPdoDataByIndocno(@RequestBody String data) {
        return tbPaopianPdoDataService.findDataTbPaopianPdoDataByIndocno(data);
    }

    /**
     * 查看记录
     *
     * @return list 对象集合返回
     */
    @CrossOrigin
    @RequestMapping(value = {"/findAll"}, method = RequestMethod.POST)
    public List<TbPaopianPdoData> findDataTbPaopianPdoData() {
        return tbPaopianPdoDataService.findDataTbPaopianPdoData();
    }


    /**
     * 查询凸度和楔形接口
     *
     * @param data json字符串
     */
    @CrossOrigin
    @RequestMapping(value = {"/findBytuxie"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData findDataTbPaopianPdoDatatuxie(@RequestBody String data) {
        return tbPaopianPdoDataService.findDataTbPaopianPdoDatatuxie(data);
    }

    /**
     * 查询连退一次项和二次项
     *
     * @param data json字符串
     */
    @CrossOrigin
    @RequestMapping(value = {"/findByonetwo"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData findDataTbPaopianPdoonetwo(@RequestBody String data) {
        return tbPaopianPdoDataService.findDataTbPaopianPdoonetwo(data);
    }

    /**
     * 查询最高的10个钢种
     *
     * @param data json字符串
     */
    @CrossOrigin
    @RequestMapping(value = {"/findHighestSteelGradeByDate"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData findHighestSteelGradeByDate(@RequestBody String data) {
        return tbPaopianPdoDataService.findHighestSteelGradeByDate(data);
    }


    /**
     * 查询最高的10个钢种
     *
     * @param data json字符串
     */
    @CrossOrigin
    @RequestMapping(value = {"/findHighestSpecificationsByDate"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData findHighestSpecificationsByDate(@RequestBody String data) {
        return tbPaopianPdoDataService.findHighestSpecificationsByDate(data);
    }


    /**
     * 宽度\厚度\钢种select分档框
     *
     * @return list 对象集合返回
     */
    @CrossOrigin
    @RequestMapping(value = {"/findselect"}, method = RequestMethod.POST)
    public List<select_value> findDataTbPaopianPdoDataselect(@RequestBody String data) {
        return tbPaopianPdoDataService.findDataTbPaopianPdoDataselect(data);
    }

    /**
     * 连退跑偏归档统计分析查询
     */
    @CrossOrigin
    @RequestMapping(value = {"/findRects"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData findlx(@RequestBody JSONObject jsonObject) {
        return tbPaopianPdoDataService.findlx(jsonObject);
    }

    /**
     * 时间区域分析
     */
    @CrossOrigin
    @RequestMapping(value = {"/findTime"}, method = RequestMethod.POST)
    @ResponseBody
    public ResultData findTime(@RequestBody String data) {
        return tbPaopianPdoDataService.findTime(data);
    }

    /**
     * 列表导出功能
     *
     * @param jsonObject
     * @param response
     */
    @PostMapping("/exportXlsx")
    public void export(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        tbPaopianPdoDataService.export(jsonObject, response);
    }

    @PostMapping("/reportpgXlsx")
    public void exportpg(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        JSONObject condition = jsonObject.getJSONObject("condition");
        List<Jpaopian_lx> jlxList = new ArrayList<>();
        List<paopian_lx> plxList = tbPaopianPdoDataDao.findlx(condition);
        List<cal_thk_wid_2130> calList = tbPaopianPdoDataDao.findDatacal();
        if (!StringUtils.isEmpty(plxList)) {
            plxList = plxList.stream().filter(x -> x.getGrade_code() != 0).collect(Collectors.toList());
            if (!StringUtils.isEmpty(calList)) {
                for (paopian_lx entity : plxList) {
                    if (entity.getGrade_code() != null) {
                        Jpaopian_lx jpaopian_lx = new Jpaopian_lx();

                        BeanUtils.copyProperties(entity, jpaopian_lx);
                        //规则号：钢种+宽度+厚度
                        String str_No = String.valueOf(entity.getGrade_code().intValue()) + entity.getWidth_code().intValue() + entity.getThick_code().intValue();
                        jpaopian_lx.setStr_No(str_No);

                        //钢种：id+name
                        //用钢种id查找钢种名称
                        cal_thk_wid_2130 cal1 = tbPaopianPdoDataServiceImpl.findstands(calList, String.valueOf(entity.getGrade_code().intValue()));
                        String str_grade_code = entity.getGrade_code().intValue() + ":" + cal1.getYp_class();
                        jpaopian_lx.setStr_grade_code(str_grade_code);

                        //宽度：最小值（前一条）+“-”+最大值（当前）
                        String str_width;
                        //获取宽度标准最大值（即当前宽度标准）
                        cal_thk_wid_2130 calwidth = tbPaopianPdoDataServiceImpl.findstands(calList, String.valueOf(entity.getWidth_code().intValue()));
                        //获取宽度标准最小值（即前一等级的宽度标准）
                        cal_thk_wid_2130 calwidth_up = tbPaopianPdoDataServiceImpl.findstands(calList, String.valueOf(entity.getWidth_code().intValue() - 1));
                        if (entity.getWidth_code().intValue() != 1) {
                            str_width = entity.getWidth_code().intValue() + ":" + calwidth_up.getWid_class() + "-" + calwidth.getWid_class();
                        } else {
                            str_width = entity.getWidth_code().intValue() + ":" + "0-" + calwidth.getWid_class();
                        }

                        jpaopian_lx.setStr_width(str_width);

                        //厚度：最小值（前一条）+“-”+最大值（当前）
                        String str_thick;
                        //获取厚度标准最大值（即当前厚度标准）
                        cal_thk_wid_2130 calthk = tbPaopianPdoDataServiceImpl.findstands(calList, String.valueOf(entity.getThick_code().intValue()));
                        //获取宽度标准最小值（即前一等级的宽度标准）
                        cal_thk_wid_2130 calthk_up = tbPaopianPdoDataServiceImpl.findstands(calList, String.valueOf(entity.getThick_code().intValue() - 1));
                        if (entity.getThick_code().intValue() != 1) {
                            str_thick = entity.getThick_code().intValue() + ":" + calthk_up.getThk_class() + "-" + calthk.getThk_class();
                        } else {
                            str_thick = entity.getThick_code().intValue() + ":" + "0-" + calthk.getThk_class();
                        }
                        jpaopian_lx.setStr_thick(str_thick);

                        //跑偏概率
                        jpaopian_lx.setStr_rate(String.valueOf(entity.getGrade_paopian_rate()));

                        //跑偏卷数
                        jpaopian_lx.setStr_num(String.valueOf(entity.getPaopian_num().intValue()));

                        //总卷数
                        jpaopian_lx.setStr_sum(String.valueOf(entity.getSum_num().intValue()));
                        jlxList.add(jpaopian_lx);
                    }
                }
            }
        }
        List<ExportJpaopian_lx> list = new ArrayList<>();
        for (Jpaopian_lx jpaopian_lx : jlxList) {
            ExportJpaopian_lx exportLedgerPlan = new ExportJpaopian_lx();
            BeanUtils.copyProperties(jpaopian_lx, exportLedgerPlan);
            list.add(exportLedgerPlan);
        }
        try {
            Map<String, Object> data = new HashMap();
            data.put("data", list);
            File file = ResourceUtils.getFile("classpath:exceltemplate\\连退品规跑偏统计.xlsx");
            TemplateExportParams templateExportParams = new TemplateExportParams(file.getPath(), false);
            templateExportParams.setDictHandler(new PlanExcelHandlerImpl());
            Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, data);
            ExcelUtilsPOI.exportExcel("连退品规跑偏统计报表", response, workbook);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 跑偏记录和酸扎曲线的归一化（固定延迟）
     */
    @Scheduled(fixedDelayString = "${scheduled.paopian.fixedDelay}")
    public void normWithTcm() {
        tbPaopianPdoDataService.normWithTcm();
    }
}
